/**
 * Created by lyp on 2017/8/1.
 */

$(document).ready(function(){
    user.loadUserList();//加载数据表格
    user.bootstrapValidator();
});

$(function () {
    $('#cfgUser').on('hide.bs.modal', function () {
        //配置角色窗口关闭时刷新表格并清除未提交的勾选项
        user.selectRole = new Array();
    })

    $('#cfgCK').on('hide.bs.modal', function () {
        //配置角色窗口关闭时刷新表格并清除未提交的勾选项
        user.selectWh = new Array();
    })
});


var user = {};
(function(res){
    //表单验证
    res.bootstrapValidator=function(){
        $("#addUserForm").bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                validating: 'glyphicon glyphicon-refresh'
            },
            fields:{
                organizationId:{
                    validators: {
                        notEmpty: {
                            message: '请选择组织机构'
                        }
                    }
                },
                name:{
                    validators: {
                        notEmpty: {
                            message: '用户名不能为空'
                        }
                    }
                },
                password:{
                    validators: {
                        notEmpty: {
                            message: '密码不能为空'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9]{6,16}$/,
                            message: '密码是6到16位由大小写字母、数字组成'
                        }
                    }
                },
                zuserPwd:{
                    validators: {
                        notEmpty: {
                            message: '请再次输入密码'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9]{6,16}$/,
                            message: '密码是6到16位由大小写字母、数字组成'
                        },
                        identical: {
                            field: 'password',
                            message: '两次输入密码不一致'
                        }
                    }
                },
                userName:{
                    validators: {
                        notEmpty: {
                            message: '用户姓名不能为空'
                        }
                    }
                },
                type:{
                    validators: {
                        notEmpty: {
                            message: '请选择用户类型'
                        }
                    }
                },
                sex:{
                    validators: {
                        notEmpty: {
                            message: '请选择性别'
                        }
                    }
                },
                phone:{
                    validators: {
                        notEmpty: {
                            message: '请输入手机号'
                        },
                        regexp: {  //同时验证手机号和固话
                            regexp: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/,
                            /* regexp: /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$)|(^((\(\d{3}\))|(\d{3}\-))?(1[34578]\d{9})$/, */
                            message: '手机号或固话格式不正确'
                        }
                    }
                },
                email:{
                    validators: {
                        regexp: {  //同时验证手机号和固话
                            regexp: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/,
                            message: '邮箱格式不正确'
                        }
                    }
                }
            }
        });
    };
    //防止表单重复验证
    res.resetValidator=function(){
        $("form.required-validate").each(function() {
            var $form = $(this);
            $form.bootstrapValidator().on("success.form.bv",function(e){
                e.preventDefault();
            });
        });
    };
    res.loadDepartment=function(){
        //打开组织机构
        $("#selectClub").click(function(){
            $("#Origin-tree").modal("show");
        });
        //关闭组织机构
        $("#cancelBtn").click(function(){
            $("#Origin-tree").modal("hide");
        });
        // $("#department").html("");
        // $.ajax({
        //     url:"../department/queryDepartment",
        //     type:"post",
        //     dataType:"json",
        //     success:function(data){
        //         var html = "<option value='0' disabled >请选择</option>";
        //         for (var i=0;i<data.length;i++){
        //             html += "<option value='"+data[i].departmentId+"'>"+data[i].departmentName+"</option>";
        //         }
        //         $("#department").html(html);
        //         $("#department").val(0);
        //     }
        // });
    };
    //打开添加用户的窗口
    res.openAddUser=function(){
        $("#addUserForm").data('bootstrapValidator').destroy();
        $('#addUserForm').data('bootstrapValidator', null);
        res.bootstrapValidator();
        res.loadDepartment();
        $('#userId').removeAttr("readonly");
        $("#addUserDialog").modal("show");
        $("#changeUser").html("添加用户");
        $(".show_none").css("display","block");
        var isTrue = true;
        res.resetAddUser(isTrue);
        $("#organizationId,#phone,#email,#pwd,#zuserPwd,#userName").val("");
        $("#userType").val(0);
        $("#sex").val(0);
    };
    //提交添加用户的form表单
    res.submitAddUser=function(){
        var $form = $('#addUserForm');
        var data = $form.data('bootstrapValidator');
        if (data) {
            // 修复记忆的组件不验证
            data.validate();
            if (!data.isValid()) {
                return false;
            }
        }
        res.resetValidator();
        var data = $("#addUserForm").serialize();
        $.ajax({
            url:"/session/register",
            type:"post",
            data:data,
            dataType:"json",
            success:function(data){
                if (data.code==200&&data.isSuccess){
                    $("#addUserDialog").modal("hide");
                    layer.msg(data.mag);
                    $("#userList").bootstrapTable("refresh");
                    $('#addUserForm').bootstrapValidator('resetForm', true);
                }else{
                    layer.msg(data.mag);
                }
            }
        });
    };

    //重置添加用户的form表单
    res.resetAddUser=function(isTrue){
        $("#addUserForm").find(":input").not(":button,#userId,#userPwd,#zuserPwd,#userType,#remark").val("");
        if(isTrue=="添加用户"){
            $("#userId").val("");
            $("#userPwd").val("");
            $("#zuserPwd").val("");
            $("#remark").val("");
        }
        $('#addUserForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
    };
    /**
     * 初始化用户信息表格
     */
    res.loadUserList=function(){
        $('#userList').bootstrapTable({
            method: 'POST',
            url:"/session/getUserList",
            queryParamsType:'',
            queryParams:function (params) {
                /*return {
                    userType:1
                }*/
            },
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            cache: false,     // 不缓存
            striped: true,    // 隔行加亮
            pagination: true, //是否显示分页
            toolbar: '#toobar',//工具列
            singleSelect:true, //单选
            clickToSelect:true,
            pageSize: 10,
            pageNumber: 1,     //初始化加载第一页，默认第一页
            pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
            search: true,
            showRefresh: true,  //是否显示刷新按钮
            clickToSelect: true,  //是否启用点击选中行
            columns:[
                {field: "select",title: "选择",checkbox: true,width: 60},
                {field: '',title: '序号',width: 60,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
                {field:"account",title:"用户名称",align:"center",valign:"middle",sortable:"true"},
                {field:"sex",title:"性别",align:"center",valign:"middle",sortable:"true",formatter:function (value,row,index) {
                    if(value==1){
                        return "男";
                    }else if(value==2){
                        return "女";
                    }else if (value == "" || value == null) {
                        return "";
                    } else {
                        return "未知";
                    }
                }},
                {field:"email",title:"邮箱",align:"center",valign:"middle",sortable:"true"},
                {field:"phone",title:"电话",align:"center",valign:"middle",sortable:"true"},
                /*{field:"type",title:"用户类型",align:"center",valign:"middle",sortable:"true",formatter: function(value, row, index){
                    return value==0?"app":"平台"
                }},*/
                {field:"createTime",title:"创建时间",align:"center",valign:"middle",sortable:"true",formatter: function (value,row,index) {
                    /*if(value==""||value==null){
                        return "";
                    }else{
                        return res.dateFormat(new Date(value),"yyyy-MM-dd")
                    }*/
                        return value;
                    }
                }
            ],
            formatLoadingMessage: function () {
                return "请稍等，正在加载中...";
            },
            formatNoMatches: function () {
                return '无符合条件的记录';
            }
        });
    };
    //显示用户类型
    /* res.showType = function (value,row,index) {
         return "平台用户"
     }*/
    res.addressFormatter=function(value,row,index){
        if (value==null||value==undefined){
            value = "";
        }
        return value;
    }
    //配置角色
    res.selectRole = new Array();
    user.cfgRole=function(userId){
        /* res.selectRole = new Array();*/
        $("#cfgUser").modal("show");
        $("#userIds").val(userId);
        $('#cfgTable').bootstrapTable('destroy');
        $('#cfgTable').bootstrapTable({
            method: 'POST',
            url:"../session/getSelectUserRoleList?id="+userId,
            cache: false,     // 不缓存
            striped: true,    // 隔行加亮
            pagination: true, //是否显示分页
            toolbar: '#cfgTool',//工具列
            singleSelect:false, //单选
            pageSize: 5,
            pageNumber: 1,     //初始化加载第一页，默认第一页
            pageList: [5], //可供选择的每页的行数（*）
            search: true,
            showRefresh: true,  //是否显示刷新按钮
            clickToSelect: true,  //是否启用点击选中行
            columns:[
                {field:"select",title: "全选",checkbox:true,width: 60},
                {field:"name",title:"角色名称",align:"center",valign:"middle",sortable:"true"}
            ],
            /*点击选中事件*/
            onCheck:function(row,ele){
                if(row.select){
                    res.selectRole.push(row);
                }
            },
            /*取消选中事件*/
            onUncheck:function(row){
                for (var j=0;j<res.selectRole.length;j++){
                    if (res.selectRole[j].id==row.id){
                        res.selectRole.splice(j,1);
                    }
                }
            },
            /*全选按钮点击事件*/
            onCheckAll:function(row){ //全选
                /*if(row.select){*/
                if(res.selectRole.length==0){
                    for(var g=0;g<row.length;g++){
                        res.selectRole.push(row[g]);
                    }
                }else{
                    for(var i=0;i<row.length;i++){
                        var isExist = false;
                        for (var j=0;j<res.selectRole.length;j++){
                            if (res.selectRole[j].id==row[i].id){
                                isExist = true;
                                break;
                            }
                        }
                        if(!isExist){
                            res.selectRole.push(row[i]);
                        }
                    }
                }
            },
            /*全选按钮取消事件*/
            onUncheckAll:function(row){ //取消全选
                for(var i=0;i<row.length;i++){
                    for (var j=0;j<res.selectRole.length;j++){
                        if (res.selectRole[j].id==row[i].id){
                            res.selectRole.splice(j,1);
                        }
                    }
                }
            },
            /*分页按钮点击事件*/
            onPageChange:function(number, size){
                var getPageData = $('#cfgTable').bootstrapTable('getData');
                for (var j=0;j<res.selectRole.length;j++){
                    for (var i=0;i<getPageData.length;i++){
                        if(res.selectRole[j].id==getPageData[i].id){
                            getPageData[i].select = true;
                            getPageData[i].name = res.selectRole[j].name;
                            $('#cfgTable').bootstrapTable('updateCell',{index:i,field:"name",value:getPageData[i].name});
                        }
                    }
                }
            },
            onLoadSuccess:function(allRows){
                //获取数据
                for (var i=0;i<allRows.length;i++){
                    if (allRows[i].select==true){
                        res.selectRole.push(allRows[i]);
                    }
                }
            },
            formatLoadingMessage: function () {
                return "请稍等，正在加载中...";
            },
            formatNoMatches: function () {
                return '无符合条件的记录';
            }
        });
    }
    /*配置基地*/
    user.cfgCK = function (userId) {
        res.selectWh = new Array();
        $("#cfgCK").modal("show");
        $("#baseIds").val(userId);
        $('#cfgCKTable').bootstrapTable('destroy');
        $('#cfgCKTable').bootstrapTable({
            method: 'POST',
            url:"../session/getCodelists?userId="+userId,
            cache: false,     // 不缓存
            striped: true,    // 隔行加亮
            pagination: true, //是否显示分页
            toolbar: '#cfgCKTool',//工具列
            singleSelect:false, //单选
            search:true,
            pageSize: 5,
            pageNumber: 1,     //初始化加载第一页，默认第一页
            pageList: [5], //可供选择的每页的行数（*）
            showRefresh: true,  //是否显示刷新按钮
            clickToSelect: true,  //是否启用点击选中行
            columns:[
                {field:"select",title: "全选",checkbox:true,width: 60,formatter:function (value,row,index) {
                    return value;
                }},
                {field:"name",title:"基地名称",align:"center",valign:"middle",sortable:"true"}
            ],
            formatLoadingMessage: function () {
                return "请稍等，正在加载中...";
            },
            formatNoMatches: function () {
                return '无符合条件的记录';
            },
            /*单击选中行*/
            onCheck:function(row,ele){
                if(row.select){
                    res.selectWh.push(row);
                }
            },
            /*单击取消选中行*/
            onUncheck:function(row){
                for (var j=0;j<res.selectWh.length;j++){
                    if (res.selectWh[j].id==row.id){
                        res.selectWh.splice(j,1);
                    }
                }
            },
            /*全选*/
            onCheckAll:function(row){ //全选
                /*if(row.select){*/
                if(res.selectWh.length==0){
                    for(var g=0;g<row.length;g++){
                        res.selectWh.push(row[g]);
                    }
                }else{
                    for(var i=0;i<row.length;i++){
                        var isExist = false;
                        for (var j=0;j<res.selectWh.length;j++){
                            if (res.selectWh[j].id==row[i].id){
                                isExist = true;
                                break;
                            }
                        }
                        if(!isExist){
                            res.selectWh.push(row[i]);
                        }
                    }
                }
            },
            /*取消全选*/
            onUncheckAll:function(row){
                for(var i=0;i<row.length;i++){
                    for (var j=0;j<res.selectWh.length;j++){
                        if (res.selectWh[j].id==row[i].id){
                            res.selectWh.splice(j,1);
                        }
                    }
                }
            },
            /*分页按钮点击事件*/
            onPageChange:function(number, size){
                var getPageData = $('#cfgCKTable').bootstrapTable('getData');
                for (var j=0;j<res.selectWh.length;j++){
                    for (var i=0;i<getPageData.length;i++){
                        if(res.selectWh[j].id==getPageData[i].id){
                            getPageData[i].select = true;
                            getPageData[i].name = res.selectWh[j].name;
                            $('#cfgCKTable').bootstrapTable('updateCell',{index:i,field:"name",value:getPageData[i].name});
                        }
                    }
                }
            },
            onLoadSuccess:function(allRows){
                //获取数据
                var getPageData = $('#cfgCKTable').bootstrapTable('getData');
                for (var i=0;i<allRows.length;i++){
                    if (allRows[i].select==true){
                        res.selectWh.push(allRows[i]);
                    }
                }
            }
        });
    };
    //基地保存
    res.saveCKConfig=function(){
        var rows = $("#cfgCKTable").bootstrapTable('getAllSelections');
        var userId =  $("#baseIds").val();
        if(res.selectWh.length == 0){
            layer.alert("请设置有权限的基地！", {icon: 1});
        }
        var data = "id="+userId;
        for (var i=0;i<res.selectWh.length;i++) {
            data += "&userBase["+i+"].id="+res.selectWh[i].id;
        }
        $.ajax({
            url:"../session/insertUserBase",
            type:"post",
            data:data,
            dataType:"json",
            success:function(data){
                if (data.code==0){
                    $("#cfgCK").modal("hide");
                    res.selectWh = new Array();
                    layer.msg(data.msg);
                }else{
                    layer.msg(data.msg);
                }
            }
        });
    };
   //角色保存
    res.saveConfig=function(){
        var userId = $("#userIds").val();
        //序列化参数
        var data = "id="+userId;
        for (var i=0;i<res.selectRole.length;i++){
            data += "&userRole["+i+"].roleId="+res.selectRole[i].id
        }
        $.ajax({
            url:"../session/insertUserRole",
            type:"post",
            data:data,
            dataType:"json",
            success:function(data){
                if (data.code==0){
                    $("#cfgUser").modal("hide");
                    res.selectRole = new Array();
                    layer.msg(data.msg);
                }else{
                    layer.msg(data.msg);
                }
            }
        });
    };

    //删除用户函数
    res.deleteUser=function(){
        var rows = $("#userList").bootstrapTable('getSelections');
        if (rows.length>0){
            var row = rows[0];
            layer.confirm('您确定要删除此记录吗？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                $.ajax({
                    url:"/session/deleteUser",
                    type:"post",
                    data:{"id":row.id},
                    dataType:"json",
                    success:function(data){
                        if (data.code==0){
                            layer.msg(data.msg);
                            $("#userList").bootstrapTable("refresh");
                            $('#addUserForm').bootstrapValidator('resetForm', true);
                        }else{
                            layer.msg(data.msg);
                        }
                    }
                });
            });
        }else{
            layer.alert("请选中一行数据！", {icon: 3});
        }
    };

    //修改用户信息
    res.openUpdateUser=function(){
        var $form = $('#addUserForm');
        var datas = $form.data('bootstrapValidator');
        if (datas) {
            // 修复记忆的组件不验证
            datas.validate();
            if (!datas.isValid()) {
                return false;
            }
        }
        res.resetValidator();
        //获取当前选中的数据
        var rows = $("#userList").bootstrapTable('getSelections');
        if (rows.length > 0){
            //打开修改窗口并初始化数据
            $("#addUserDialog").modal("show");
            $("#changeUser").html("修改用户");
            $("#idUser").val(rows[0].id);
            $("#organizationId").val(rows[0].organizationId);
            $("#phone").val(rows[0].phone);
            $("#email").val(rows[0].email);
            $("#userName").val(rows[0].userName);
            $("#account").val(rows[0].account);
            $("#sex").val(rows[0].sex);
            $("#userType").val(rows[0].type);
            var tree =  $.fn.zTree.getZTreeObj("treeDemo");
            tree.expandAll(true);
            var organizationId = rows[0].organizationId;
            var node = tree.getNodeByParam("id",organizationId, null);
            tree.checkNode(node,true,true,false);
            var orgName = node.orgName;
            $("#organizationName").val(orgName);

            // $.fn.zTree.getZTreeObj("treeDemo").checkNode(node,true,true);
            // $("#organizationName").val(rows[0].organizationId);
            // var organizationId=rows[0].organizationId;
            // console.log(organizationId);
        }else{
            layer.alert("请选中一行数据！", {icon: 3});
        }
    };

    //时间格式化方法
    res.dateFormat=function (now,mask) {
        var d = now;
        var zeroize = function (value, length)
        {
            if (!length) length = 2;
            value = String(value);
            for (var i = 0, zeros = ''; i < (length - value.length); i++)
            {
                zeros += '0';
            }
            return zeros + value;
        };

        return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0)
        {
            switch ($0)
            {
                case 'd': return d.getDate();
                case 'dd': return zeroize(d.getDate());
                case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
                case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
                case 'M': return d.getMonth() + 1;
                case 'MM': return zeroize(d.getMonth() + 1);
                case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
                case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
                case 'yy': return String(d.getFullYear()).substr(2);
                case 'yyyy': return d.getFullYear();
                case 'h': return d.getHours() % 12 || 12;
                case 'hh': return zeroize(d.getHours() % 12 || 12);
                case 'H': return d.getHours();
                case 'HH': return zeroize(d.getHours());
                case 'm': return d.getMinutes();
                case 'mm': return zeroize(d.getMinutes());
                case 's': return d.getSeconds();
                case 'ss': return zeroize(d.getSeconds());
                case 'l': return zeroize(d.getMilliseconds(), 3);
                case 'L': var m = d.getMilliseconds();
                    if (m > 99) m = Math.round(m / 10);
                    return zeroize(m);
                case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
                case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
                case 'Z': return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
                default: return $0.substr(1, $0.length - 2);
            }
        });
    }
})(user);




